﻿$(function () {
    var voteList = function () {
        this.Init();
    };

    voteList.prototype = {
        // 初始化页面
        Init: function () {
            this.GetVoteInfo();
        },

        // 异步获取投票状态
        GetVoteInfo: function () {
            // 非员工
            if (actionConfig.IsNotEmployee == "True") {
                $("#pagecontent").html("<div style='text-align: center;padding-top:30%'><div class='smilePic'></div><div><h3>谢谢您的参与，请关注MC2企业号！</h3></div></div>").trigger("create");;
                $("#pagecontent").show();
                return;
            }

            // 不存在该活动
            if (actionConfig.ActionID == -1) {
                $("#pagecontent").html("<div style='text-align: center;padding-top:30%'><div class='smilePic'></div><div><h3>没有找到该活动！</h3></div></div>").trigger("create");;
                $("#pagecontent").show();
                return;
            }

            // 投票赞未开始
            if (actionConfig.VotingStatus == -1) {
                $("#pagecontent").html("<div style='text-align: center;padding-top:30%'><div class='smilePic'></div><div><h3>活动暂未开始，稍后再来！<br/>开始时间: " + actionConfig.VoteBeginTime + "</h3></div></div>").trigger("create");;
                $("#pagecontent").show();
                return;
            }

            $("#pagecontent").show();
            // 投票进行中 
            $.mobile.loading('show');
            var cur = this;
            $.ajax({
                type: "Get",
                url: "GetVoteInfo?actionId=" + actionConfig.ActionID,
                data: null,
                dataType: "json",
                success: function (response) {
                    $.mobile.loading('hide');
                    var votinglist = response.VotingList;
                    allVotingInfo = votinglist;
                    isOnlyShow = (votinglist.length == 1 && votinglist[0].VoteItemList.length == 1);

                    var actionInfo = JSON.parse(actionConfig.ActionInfo);
                    var html = [];
                    // 投票进行中 
                    html.push("<ul>")
                    for (var i = 0; i < votinglist.length; i++) {
                        var dis = (i == 0) ? "" : "display:none";
                        var vote = votinglist[i];
                        var docwidth = document.body.clientWidth;
                        html.push("<li name='voteitemli' tip='" + vote.VoteType + "' style='background: #ECECEC;margin-bottom: 70px;" + dis + "' index='" + (i + 1) + "'>");
                        // 活动描述
                        html.push("<div style='width: 100%;margin: 0 auto;background:#fff'><div style='width: 94%;margin: 0 auto;'><h2 style='margin:0;padding-top: 0.6em;padding-bottom: 0.2em;text-align:center'>" + actionInfo.ActionName + "</h2></div>");
                        html.push("<div  class='pro_info' style=' margin-bottom: 0.5em;margin: 0 auto;width: 94%;padding-bottom:1.2em;font-size: 18px;'><b style='color:#4739C0;'>" + actionInfo.ActionDesc + "</b><div style='border-bottom:1px dashed #000000;padding-top: 0.8em'></div></div></div>");
                        if (vote.VoteType == 0) {
                            html.push(cur.PaintNormalItem(vote));
                        } else if (vote.VoteType == 1) {
                            html.push(cur.PaintPicItem(vote));
                        } else {
                            html.push(cur.PaintVideoItem(vote));
                        }

                        html.push("</li>");
                    }
                    html.push("</ul>");
                    $("#content").html(html.join("")).trigger("create");
                    if (isOnlyShow) {
                        $("#footer").hide();
                    }
                    if (votinglist.length > 1) {
                        $("#currentVote").html("1/");
                        $("#totalVote").html(votinglist.length);
                        $("#saveoptionstext").html("下一项");
                    }
                },
                error: function () {
                    $.mobile.loading('hide');
                    alert("网络异常，稍后重试！");
                }
            });

            // 投票
            $("#content").on("click", "div[name=voteitemactive]", function () {
                var currentvoteitem = $(this);
                if (currentvoteitem.hasClass('active')) {
                    currentvoteitem.removeClass('active').text("投票");
                } else {
                    currentvoteitem.addClass('active').text("取消");
                }
            });

            // 视频播放
            $("#content").on("click", "img[name=playvideo]", function () {
                var videoid = $(this).attr('tip');
                if (!videoid || videoid == "") { return; }
                var pageWidth = $(document.body).width();
                var hight = 230;
                if (pageWidth <= 330) { hight = 180; } else if (pageWidth <= 490) { hight == 230; } else { hight == 280; }
                $(window).ShowDialog({ width: pageWidth - 20, height: hight, title: "点击播放视频", src: "video?videoId=" + videoid });
            });
            $("#content").on("click", "img[name=playicon]", function () {
                var videoid = $(this).attr('tip');
                if (!videoid || videoid == "") { return; }
                var pageWidth = $(document.body).width();
                var hight = 230;
                if (pageWidth <= 330) { hight = 180; } else if (pageWidth <= 490) { hight == 230; } else { hight == 280; }
                $(window).ShowDialog({ width: pageWidth - 20, height: hight, title: "点击播放视频", src: "video?videoId=" + videoid });
            });
        },

        // 文字投票
        PaintNormalItem: function (vote) {
            var html = [];
            if (!isOnlyShow) {
                html.push("<div style='width: 100%;margin: 0 auto;background:#fff'><div style='width:100%;background:#ffffff'><h3 style='margin: 0;padding: 0.5em;text-align: center;'>" + vote.VoteName + "</h3></div>");
                html.push("<div style='width:94%;  margin:0 auto;  padding-bottom: 1.2em;font-size: 16px;' class='pro_info'>" + vote.GroupDesc + "</div></div>");
            }
            html.push("<fieldset style='width: 93%;margin: 0 auto;' data-role='controlgroup' data-iconpos='right'>");
            var optionIndex = 0;
            for (var j = 0; j < vote.VoteItemList.length; j++) {
                var voteItem = vote.VoteItemList[j];
                var checkboxName = "voteoption_" + voteItem.ItemID;
                var optionChar = (1 + j);
                html.push("<input type='checkbox' name='" + checkboxName + "' id='" + checkboxName + "'><label for='" + checkboxName + "'>" + optionChar + "、" + voteItem.ItemName + "</label>");
            }

            html.push("</fieldset>");

            return html.join("");
        },

        // 图文投票
        PaintPicItem: function (vote) {
            var html = [];
            html.push("<div class='marketing_list' style='padding:0px'>");
            if (!isOnlyShow) {
                html.push("<div style='width: 100%;margin: 0 auto;background:#fff'><div style='width:100%;background:#ffffff'><h3 style='margin: 0;padding: 0.5em;text-align: center;'>" + vote.VoteName + "</h3></div>");
                html.push("<div style='width:94%;  margin:0 auto;  padding-bottom: 1.2em;font-size: 16px;' class='pro_info'>" + vote.GroupDesc + "</div></div>");
            }
            for (var j = 0; j < vote.VoteItemList.length; j++) {
                var voteItem = vote.VoteItemList[j];
                html.push("<div class='divitem'><div class='product_img'>");
                html.push("<img height='auto' src='/upload/" + voteItem.ImageUrl + "' alt='' title=''></div>");

                var indexText = isOnlyShow ? voteItem.ItemName : (j + 1) + "、" + voteItem.ItemName; 
                html.push("<div class='pro_info'><div><b>" + indexText + "</b></div><div style='padding-top: 10px;'> " + voteItem.Introduction + "</div>");
                if (!isOnlyShow) {
                    html.push("<div class='voteitembtn' tip='" + voteItem.ItemID + "' name='voteitemactive'>投票</div><div style='height:0.8em;width:100%'></div>");
                }
                html.push("</div></div>");
            }
            html.push(" </div>");
            return html.join("");
        },

        // 视频投票
        PaintVideoItem: function (vote) {
            var html = [];
            html.push("<div class='marketing_list'  style='padding:0px'>");
            if (!isOnlyShow) {
                html.push("<div style='width: 100%;margin: 0 auto;background:#fff'><div style='width:100%;background:#ffffff'><h3 style='margin: 0;padding: 0.5em;text-align: center;'>" + vote.VoteName + "</h3></div>");
                html.push("<div style='width:94%;  margin:0 auto;  padding-bottom: 1.2em;font-size: 16px;' class='pro_info'>" + vote.GroupDesc + "</div></div>");
            }

            for (var j = 0; j < vote.VoteItemList.length; j++) {
                var voteItem = vote.VoteItemList[j];
                html.push("<div class='divitem'><div class='product_img'>");
                html.push("<img name='playicon' src='../ResStatic/CSS/Images/play.png'  tip='" + voteItem.RelationVideo + "' style='width: 3.5em;  height: 3.5em;  z-index: 99;  position: absolute;  right: 0em;  bottom: 0.5em;'/>");
                html.push("<img height='auto' name='playvideo' src='" + voteItem.ImageUrl + "' tip='" + voteItem.RelationVideo + "'></div>");
                var indexText = isOnlyShow ? voteItem.ItemName : (j + 1) + "、" + voteItem.ItemName;
                html.push("<div class='pro_info'><div><b>" + indexText + "</b></div><div  style='padding-top: 10px;'> " + voteItem.Introduction + "</div>");
                if (!isOnlyShow) {
                    html.push("<div class='voteitembtn' tip='" + voteItem.ItemID + "' name='voteitemactive'>投票</div><div style='height:0.8em;width:100%'></div>");
                }
                 html.push("</div></div>");
            }
            html.push(" </div>");
            return html.join("");
        },

        // 检查选择项
        CheckSelect: function () {
            var currentItem = $("#content li[name=voteitemli]:visible");
            var currentItemVoteType = currentItem.attr("tip");
            var slectedCount = 0;

            // 当前投票
            if (currentItemVoteType == "1" || currentItemVoteType == "2") {
                currentItem.find("div[name='voteitemactive']").each(function () {
                    if ($(this).hasClass('active')) {
                        slectedCount = slectedCount + 1;
                    }
                });
            } else {
                currentItem.find("input[type='checkbox']").each(function () {
                    if ($(this).is(':checked')) {
                        slectedCount = slectedCount + 1;
                    }
                });
            }

            var voteIndex = currentItem.attr("index") - 1;
            var currentVoteInfo = allVotingInfo[voteIndex];

            if (slectedCount < currentVoteInfo.MinSelectedCount) {
                alert("至少选择" + currentVoteInfo.MinSelectedCount + "项参与投票！");
                return false;
            }
            if (slectedCount > currentVoteInfo.MaxSelectedCount) {
                alert("最多选择" + currentVoteInfo.MaxSelectedCount + "项参与投票！");
                return false;
            }

            return true
        },

        // 下一步
        NextStep: function () {
            var vaild = this.CheckSelect();
            if (!vaild) { return; }
            var itemlist = $("#content li[name=voteitemli]");
            // 如果是最后一项，保存投票结果
            var currentIndex = $("#content li[name=voteitemli]:visible").attr("index");
            if (currentIndex == itemlist.length) {
                this.SaveSelectedOptions();
            } else {
                //多个投票选项跳转下一项
                this.ShowNext();
            }
        },

        // 显示下一项投票
        ShowNext: function () {
            var itemlist = $("#content li[name=voteitemli]");

            // 只有一项投票不支持左右滑动
            if (itemlist.length == 1) { return; }

            // 最后一项提示
            var currentItem = $("#content li[name=voteitemli]:visible");
            var currentItemIndex = currentItem.attr("index");
            if (currentItemIndex == itemlist.length) { alert("已经是最后一项！"); return; }

            // 必须完成当前投票
            var vaild = this.CheckSelect();
            if (!vaild) { return; }

            if (currentItemIndex == (itemlist.length - 1))
            { $("#saveoptions").html("我要投票"); }

            // 隐藏当前项，显示下一项
            currentItem.hide();
            $(itemlist[currentItemIndex]).show();
        },

        // 显示上一项投票
        ShowPrevious: function () {
            var itemlist = $("#content li[name=voteitemli]");

            // 只有一项投票不支持左右滑动
            if (itemlist.length == 1) { return; }

            // 第一项提示
            var currentItem = $("#content li[name=voteitemli]:visible");
            var currentItemIndex = currentItem.attr("index");
            if (currentItemIndex == "1") { alert("已经是第一项！"); return; }

            if (currentItemIndex == itemlist.length)
            { $("#saveoptions").html("下一项"); }

            // 隐藏当前项，显示下一项
            currentItem.hide();
            $(itemlist[currentItemIndex - 2]).show();
        },

        // 获取选项，并保存
        SaveSelectedOptions: function () {
            // 判断投票状态
            if (actionConfig.VotingStatus == 2) { alert("您已投票，不可重复投票！"); $("#footer").show(); return; } else if (actionConfig.VotingStatus == 3) { alert("您来迟了，投票已经结束！"); $("#footer").show(); return; }

            $.mobile.loading('show');
            $("#footer").hide();
            var selectedoptions = [];
            // 文字选票统计
            var cblist = $("input[type='checkbox']:checkbox:checked");
            if (cblist && cblist.length > 0) {
                var alloptions = cblist.each(function () {
                    selectedoptions.push($(this).attr("name").split('_')[1]);
                });
            }

            // 图文，视频选票统计
            var activelist = $("div[name='voteitemactive'][class='voteitembtn active']");
            if (activelist && activelist.length > 0) {
                activelist.each(function () {
                    selectedoptions.push($(this).attr("tip"));
                });
            }

            var userVoteInfo = {
                "ActionID": actionConfig.ActionID,
                "UserInfo": JSON.parse(actionConfig.UserInfo),
                "SelectedOptions": selectedoptions
            };
            var data = JSON.stringify(userVoteInfo);
            $.ajax({
                type: "Post",
                url: "SaveVotingResult",
                data: data,
                contentType: "application/json",//这个一定要加上哟！
                dataType: "json",
                success: function (response) {
                    //隐藏加载器  
                    $.mobile.loading('hide');
                    var retcode = response.RetCode;
                    if (retcode == 0) {
                        // 投票完成
                        $("#pagecontent").html("<div style='text-align: center;padding-top:30%'><div class='smilePic'></div><div><h2>投票成功，感谢您的支持！</h2></div></div>").trigger("create");;
                    } else {
                        alert("您已投票，不可重复投票！");
                        $("#footer").show();
                    }
                },
                error: function () {
                    $.mobile.loading('hide');
                    alert("网络异常，稍后重试！");
                    $("#footer").show();
                }
            });
        }
    };

    var votemodel = new voteList();

    // 下一步
    $("#saveoptions").on("click", function () {
        votemodel.NextStep();
    });

    // 屏幕宽度变化
    $(window).resize(function () {
        var docwidth = document.body.clientWidth;
        $("#content li[name=voteitemli]").width(docwidth);
        $("#content").width(docwidth * $("#content li[name=voteitemli]").length + 100)
    });

    // 左滑动
    $(document).on("swipeleft", "#pagecontent", function () {
        votemodel.ShowNext();
    });

    // 右滑动
    $(document).on("swiperight", "#pagecontent", function () {
        votemodel.ShowPrevious();
    });
});


